const GROUP_NAME = 'download';
const fs = require('fs');
const Config = require('../config/index');
const Joi = require('joi');
const walk = require('walk');
const MIME = require('../utils/MIME').MIME;
module.exports = [{
    method: 'POST',
    path: `/${GROUP_NAME}`,
    config: {
        handler: function (request, reply) {
            // console.log(`fileName=${request.payload.fileName}`);
            let file = request.payload.fileName,
                path = Config.publicFolder + Config.uploadFolder + "/" + file,
                ext = file.substr(file.lastIndexOf('.') + 1);
            // console.log(`ext=${ext}`);
            fs.readFile(path, function (error, content) {
                if (error) return reply("file not found");
                let contentType = '';
                for (let key in MIME) {
                    // console.log(`contentType=${MIME[key]}`);
                    if (key === ext) contentType = MIME[key];
                }
                if (contentType === '') contentType = 'application/json';
                reply(content).header('Content-Type', contentType).header("Content-Disposition", "attachment; filename=" + file);
            });
        },
        tags: ['api', GROUP_NAME],
        auth: false, //false 配置为不通过jwt验证
        description: '下载文件接口（直接返回file文件）',
        validate: {
            payload: Joi.object({
                fileName: Joi.string().required()
            })
        }
    },
}, {
    method: 'POST',
    path: `/${GROUP_NAME}/getPath`,
    config: {
        handler: function (request, reply) {
            // console.log(`fileName=${request.payload.fileName}`);
            let file = request.payload.fileName,
                publicFolder = new String(Config.publicFolder),
                uploadFolder = new String(Config.uploadFolder),
                path = `${publicFolder}${uploadFolder}/${file}`;
            fs.readFile(path, function (error, content) {
                if (error) return reply({
                    code: '-1',
                    msg: error
                });
                reply({
                    code: '0',
                    msg: 'ok',
                    path: `http://${Config.proxyHost}:${Config.proxyPort}${Config.uploadFolder}/${file}`
                })
            });
        },
        tags: ['api', GROUP_NAME],
        auth: false, //false 配置为不通过jwt验证
        description: '下载文件接口（返回文件路径）',
        validate: {
            payload: Joi.object({
                fileName: Joi.string().required()
            })
        }
    },
}, {
    method: 'POST',
    path: `/${GROUP_NAME}/getFileList`,
    config: {
        handler: function (request, reply) {
            var files = [];
            // Walker options
            var walker = walk.walk(Config.publicFolder + Config.uploadFolder, {
                followLinks: false
            });

            walker.on('file', function (root, stat, next) {
                // Add this file to the list of files
                files.push(`http://${Config.proxyHost}:${Config.proxyPort}${Config.uploadFolder}/${stat.name}`);
                next();
            });

            walker.on('end', function () {
                return reply({
                    code: '0',
                    msg: 'ok',
                    fileList: files
                });
            });
        },
        tags: ['api', GROUP_NAME],
        auth: false, //false 配置为不通过jwt验证
        description: '获取上传文件夹下文件列表',
        validate: {

        }
    },
}]